import { config } from '../config.js';
import ResponseFormatter from '../utils/ResponseFormatter.js';

/**
 * 中间件管理器 - 统一管理所有中间件的注册和配置
 */
export class MiddlewareManager {
    constructor() {
        this.middlewares = new Map();
        this.globalMiddlewares = [];
        this.routeMiddlewares = new Map();
    }

    /**
     * 注册中间件
     * @param {string} name - 中间件名称
     * @param {Function} middleware - 中间件函数
     * @param {Object} options - 中间件选项
     */
    register(name, middleware, options = {}) {
        if (typeof middleware !== 'function') {
            throw new Error(`Middleware '${name}' must be a function`);
        }

        this.middlewares.set(name, {
            middleware,
            options,
            enabled: options.enabled !== false,
            priority: options.priority || 0
        });

        console.log(`✓ Middleware '${name}' registered successfully`);
    }

    /**
     * 获取中间件
     * @param {string} name - 中间件名称
     * @returns {Function|null} 中间件函数
     */
    get(name) {
        const middlewareInfo = this.middlewares.get(name);
        return middlewareInfo && middlewareInfo.enabled ? middlewareInfo.middleware : null;
    }

    /**
     * 启用中间件
     * @param {string} name - 中间件名称
     */
    enable(name) {
        const middlewareInfo = this.middlewares.get(name);
        if (middlewareInfo) {
            middlewareInfo.enabled = true;
            console.log(`✓ Middleware '${name}' enabled`);
        }
    }

    /**
     * 禁用中间件
     * @param {string} name - 中间件名称
     */
    disable(name) {
        const middlewareInfo = this.middlewares.get(name);
        if (middlewareInfo) {
            middlewareInfo.enabled = false;
            console.log(`✓ Middleware '${name}' disabled`);
        }
    }

    /**
     * 添加全局中间件
     * @param {string} name - 中间件名称
     */
    addGlobal(name) {
        if (this.middlewares.has(name)) {
            this.globalMiddlewares.push(name);
            console.log(`✓ Middleware '${name}' added to global middlewares`);
        } else {
            throw new Error(`Middleware '${name}' not found`);
        }
    }

    /**
     * 为特定路由添加中间件
     * @param {string} route - 路由路径
     * @param {string|Array} middlewareNames - 中间件名称或名称数组
     */
    addToRoute(route, middlewareNames) {
        const names = Array.isArray(middlewareNames) ? middlewareNames : [middlewareNames];
        
        if (!this.routeMiddlewares.has(route)) {
            this.routeMiddlewares.set(route, []);
        }
        
        const routeMiddlewares = this.routeMiddlewares.get(route);
        
        names.forEach(name => {
            if (this.middlewares.has(name)) {
                routeMiddlewares.push(name);
                console.log(`✓ Middleware '${name}' added to route '${route}'`);
            } else {
                throw new Error(`Middleware '${name}' not found`);
            }
        });
    }

    /**
     * 获取全局中间件数组
     * @returns {Array} 全局中间件函数数组
     */
    getGlobalMiddlewares() {
        return this.globalMiddlewares
            .map(name => this.get(name))
            .filter(middleware => middleware !== null)
            .sort((a, b) => {
                const aInfo = this.middlewares.get(this.globalMiddlewares.find(name => this.get(name) === a));
                const bInfo = this.middlewares.get(this.globalMiddlewares.find(name => this.get(name) === b));
                return (bInfo?.priority || 0) - (aInfo?.priority || 0);
            });
    }

    /**
     * 获取特定路由的中间件数组
     * @param {string} route - 路由路径
     * @returns {Array} 路由中间件函数数组
     */
    getRouteMiddlewares(route) {
        const middlewareNames = this.routeMiddlewares.get(route) || [];
        return middlewareNames
            .map(name => this.get(name))
            .filter(middleware => middleware !== null);
    }

    /**
     * 获取所有已注册的中间件信息
     * @returns {Object} 中间件信息对象
     */
    getInfo() {
        const info = {
            total: this.middlewares.size,
            enabled: 0,
            disabled: 0,
            global: this.globalMiddlewares.length,
            routes: this.routeMiddlewares.size,
            middlewares: {}
        };

        this.middlewares.forEach((middlewareInfo, name) => {
            if (middlewareInfo.enabled) {
                info.enabled++;
            } else {
                info.disabled++;
            }

            info.middlewares[name] = {
                enabled: middlewareInfo.enabled,
                priority: middlewareInfo.priority,
                options: middlewareInfo.options
            };
        });

        return info;
    }

    /**
     * 清空所有中间件
     */
    clear() {
        this.middlewares.clear();
        this.globalMiddlewares = [];
        this.routeMiddlewares.clear();
        console.log('✓ All middlewares cleared');
    }
}

// 创建全局中间件管理器实例
export const middlewareManager = new MiddlewareManager();

// 导出默认实例
export default middlewareManager;